#include "unifiedpagerenderer.h"
#include "processingsettings.h"
#include "systemconfig.h"
#include "systemconfigmanager.h"
#include "dpiservice.h"
#include "dpicalculationservice.h"
#include "margincalculationservice.h"
#include "dualcanvasrenderer.h"
#include "virtualcanvasmanager.h"
#include "displaycanvascalculator.h"
#include "globalpagemanager.h"
// QtCore / QtGui (use non-prefixed includes)
#include <QObject>
#include <QRect>
#include <QSize>
#include <QString>
#include <QVector>
#include <QList>
#include <QHash>
#include <QDebug>
#include <QPoint>
#include <QImage>
#include <QPainter>
#include <QPdfWriter>
#include <QFont>
#include <QColor>
#include <QPen>
// A4尺寸常量（毫米）
const double UnifiedPageRenderer::A4_WIDTH_MM = 210.0;
const double UnifiedPageRenderer::A4_HEIGHT_MM = 297.0;
UnifiedPageRenderer::UnifiedPageRenderer(QObject* parent)
    : QObject(parent)
    , m_settings(nullptr)
    , m_highlightedThumbnailIndex(-1)
    , m_totalThumbnails(0)
    , m_columnMode(1)
    , m_hasHighlight(false)
  {
}
UnifiedPageRenderer::~UnifiedPageRenderer()
{
    delete m_settings;
}
void UnifiedPageRenderer::setRenderSettings(const ProcessingSettings& settings)
{
    if (m_settings) {
        delete m_settings;
    } else {
    }
    m_settings = new ProcessingSettings(settings);
    // 页码渲染设置已统一到ProcessingSettings，无需额外更新
}
void UnifiedPageRenderer::setPageContent(const QImage& pageContent)
{
    m_pageContent = pageContent;
}
const ProcessingSettings* UnifiedPageRenderer::getCurrentSettings() const
{
    return m_settings;
}
// === Martin Fowler重构：新的双画布渲染接口 ===
void UnifiedPageRenderer::renderToWidget(QPainter* painter, const QRect& targetRect, const QImage& content,
                                        int pageNumber, int totalPages)
{
    if (!painter || content.isNull()) {
        return;
    }

    emit renderingStarted();
    renderToWidgetLegacy(painter, targetRect, content, pageNumber, totalPages);
    emit renderingFinished();
}
void UnifiedPageRenderer::renderToPDF(QPdfWriter* writer, QPainter* painter, const QImage& content,
                                     int pageNumber, int totalPages)
{
    if (!writer || !painter || content.isNull()) {
        return;
    }

    // 🎯 使用传统渲染系统进行PDF导出
    emit renderingStarted();
    renderToPDFLegacy(writer, painter, content, pageNumber, totalPages);
    emit renderingFinished();
}
// === 兼容性接口：保持向后兼容 ===
void UnifiedPageRenderer::renderToWidget(QPainter* painter, const QRect& targetRect, int pageNumber, int totalPages)
{
    if (!painter || !m_settings) return;
    emit renderingStarted();
    // 计算页面布局
    PageLayout layout = calculatePageLayout(targetRect);
    // 绘制页面内容
    if (!m_pageContent.isNull()) {
        drawPageContent(painter, layout.contentArea);
    }
    // 绘制页边距（仅在非零边距时绘制辅助线，可选）
    // drawPageMargins(painter, layout);
    // 绘制页码
    if (m_settings->pageNumber.enabled) {
        drawPageNumber(painter, layout, pageNumber, totalPages);
    }
    // 绘制页眉页脚
    drawHeaderFooter(painter, layout);
            // 高亮现在直接在组合页面渲染时绘制，不需要在这里绘制
    emit renderingFinished();
}
void UnifiedPageRenderer::renderToPDF(QPdfWriter* writer, QPainter* painter, int pageNumber, int totalPages)
{
    // 兼容性接口：使用当前页面内容调用新接口
    if (!m_pageContent.isNull()) {
        renderToPDF(writer, painter, m_pageContent, pageNumber, totalPages);
    } else {
        renderToPDFLegacyDirect(writer, painter, pageNumber, totalPages);
    }
}
void UnifiedPageRenderer::renderToPDFLegacyDirect(QPdfWriter* writer, QPainter* painter, int pageNumber, int totalPages)
{
    if (!writer || !painter || !m_settings) return;
    emit renderingStarted();

    // Martin Fowler重构：使用DpiService获取PDF导出DPI
    double pdfDpi = DpiSvc.getDpiForPurpose(DpiService::DpiPurpose::PdfExport);
    // 明确设置写入器分辨率，确保所有路径都使用期望DPI
    writer->setResolution(static_cast<int>(pdfDpi));

    // PDF渲染使用整个页面区域
    QRect pdfRect(0, 0, writer->width(), writer->height());

    // 🚀 关键修改：使用与主窗口显示相同的renderToWidget方法
    // 这确保PDF导出效果与主窗口显示完全一致
    renderToWidget(painter, pdfRect, pageNumber, totalPages);

    emit renderingFinished();
}
void UnifiedPageRenderer::drawPageContent(QPainter* painter, const QRect& contentArea)
{
    if (m_pageContent.isNull()) return;
    painter->save();
    // Martin Fowler重构：使用SystemConfig的ProcessingQuality枚举
    const SystemConfig& config = ConfigMgr.getConfig();
    ProcessingQuality quality = config.processingQuality;
    int currentDpi = config.getProcessingDpi();
    // 根据ProcessingQuality枚举设置渲染质量
    switch (quality) {
        case ProcessingQuality::Extreme:
        case ProcessingQuality::High:
            // 高质量：启用所有渲染优化
            painter->setRenderHint(QPainter::Antialiasing, true);
            painter->setRenderHint(QPainter::SmoothPixmapTransform, true);
            painter->setRenderHint(QPainter::TextAntialiasing, true);
            break;
        case ProcessingQuality::Standard:
            // 标准质量：启用基本抗锯齿
            painter->setRenderHint(QPainter::Antialiasing, true);
            painter->setRenderHint(QPainter::SmoothPixmapTransform, true);
            break;
        case ProcessingQuality::Fast:
            // 快速模式：优先性能
            // 使用默认渲染设置，不启用额外的渲染提示
            break;
    }
    // 低DPI（<150）：使用默认渲染，保持性能
    // 屏幕预览几何稳定：始终按内容区域适配，不因DPI变化而改变几何尺寸
    QSize imageSize = m_pageContent.size();
    double scaleX = (double)contentArea.width() / imageSize.width();
    double scaleY = (double)contentArea.height() / imageSize.height();
    double scale = qMin(scaleX, scaleY);
    int finalWidth = (int)(imageSize.width() * scale);
    int finalHeight = (int)(imageSize.height() * scale);
    // 在内容区域内居中
    int x = contentArea.x() + (contentArea.width() - finalWidth) / 2;
    int y = contentArea.y() + (contentArea.height() - finalHeight) / 2;
    QRect drawRect(x, y, finalWidth, finalHeight);
    // 根据DPI应用图像增强处理
    QImage enhancedImage = applyDPIEnhancement(m_pageContent);
    bool wasEnhanced = (enhancedImage.cacheKey() != m_pageContent.cacheKey());
    // 明确在导出阶段进行下采样：将嵌入PDF的位图尺寸固定为内容区域像素尺寸
    QImage scaledForPdf;
    if (enhancedImage.size() != drawRect.size()) {
        scaledForPdf = enhancedImage.scaled(drawRect.size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    } else {
        scaledForPdf = enhancedImage;
    }
    // 使用无缩放绘制方式，确保PDF实际嵌入的位图数据就是下采样后的尺寸
    painter->drawImage(QPoint(drawRect.x(), drawRect.y()), scaledForPdf);
    painter->restore();
}
void UnifiedPageRenderer::drawPageMargins(QPainter* painter, const PageLayout& layout)
{
    // 可选：绘制页边距辅助线（主要用于调试或预览模式）
    painter->save();
    painter->setPen(QPen(QColor(200, 200, 200), 1, Qt::DashLine));
    // 绘制内容区域边界
    painter->drawRect(layout.contentArea);
    painter->restore();
}
void UnifiedPageRenderer::drawPageNumber(QPainter* painter, const PageLayout& layout, int pageNumber, int totalPages)
{
    // 重构：直接使用新的渲染方法，消除PhysicalPageNumberRenderer中间层
    renderPageNumberDirect(painter, layout, pageNumber, totalPages);
}
void UnifiedPageRenderer::renderPageNumberDirect(QPainter* painter, const PageLayout& layout, int pageNumber, int totalPages)
{
    if (!m_settings->pageNumber.enabled || pageNumber <= 0) {
        return;
    }
    painter->save();
    try {
        // 直接在显示坐标系中工作，无需DPI变换
        
        
        QString pageText = m_settings->pageNumber.formatPageNumber(pageNumber, totalPages);
        
        // 应用字体和颜色设置
        QFont renderFont = m_settings->pageNumber.font;
        // 根据显示区域调整字体大小（保持可读性）
        int baseFontSize = renderFont.pointSize();
        if (baseFontSize <= 0) {
            baseFontSize = renderFont.pixelSize();
        }
        
        // === 关键修复：根据渲染DPI调整字体大小，确保PDF导出和预览视觉一致 ===
        QSizeF pageSizeMM(A4_WIDTH_MM, A4_HEIGHT_MM);
        // 计算显示区域的实际DPI
        double displayDPI = (layout.pageRect.width() * 25.4) / pageSizeMM.width();
        
        // 基准DPI：150（PageView预览使用的固定DPI）
        const double BASE_DPI = 150.0;
        
        
        // 修复：统一使用缩放策略，避免预览和导出的字体大小不一致
        // 页码应该相对于页面内容保持合理比例，不要太突出
        // 
        // 策略调整：
        // 1. 预览模式(150 DPI)：使用0.75x缩放，让页码更协调
        // 2. 高DPI导出：按比例缩放以保持与预览一致的视觉大小
        
        const double PREVIEW_SCALE_FACTOR = 0.75;  // 预览模式下缩小到75%
        
        if (displayDPI > BASE_DPI * 1.2) {
            // 高DPI模式（PDF导出）：计算缩放后的点数以保持视觉大小
            // 公式：adjustedSize = baseFontSize * PREVIEW_SCALE_FACTOR * (BASE_DPI / displayDPI)
            double scaleFactor = PREVIEW_SCALE_FACTOR * (BASE_DPI / displayDPI);
            int adjustedFontSize = qMax(5, qRound(baseFontSize * scaleFactor));
            renderFont.setPointSize(adjustedFontSize);
        } else {
            // 正常预览模式：也应用缩放因子，让页码更协调
            int adjustedFontSize = qMax(6, qRound(baseFontSize * PREVIEW_SCALE_FACTOR));
            renderFont.setPointSize(adjustedFontSize);
        }
        
        painter->setFont(renderFont);
        painter->setPen(m_settings->pageNumber.color);
        // 使用网格系统获取毫米偏移
        QPointF offsetMM = m_settings->pageNumber.gridState.toMillimeterOffset();
        QPointF positionMM = PagePositionSystem::calculatePosition(
            QRectF(0, 0, pageSizeMM.width(), pageSizeMM.height()),
            m_settings->pageNumber.position,
            offsetMM
        );
        // 将毫米坐标转换为显示坐标
        double displayScaleX = static_cast<double>(layout.pageRect.width()) / pageSizeMM.width();
        double displayScaleY = static_cast<double>(layout.pageRect.height()) / pageSizeMM.height();
        QPointF displayPos(
            layout.pageRect.left() + positionMM.x() * displayScaleX,
            layout.pageRect.top() + positionMM.y() * displayScaleY
        );

        
        // 计算文本对齐偏移
        QFontMetrics fontMetrics(renderFont);
        QSizeF textSize = fontMetrics.size(Qt::TextSingleLine, pageText);
        QPointF textOrigin = PagePositionSystem::calculateTextOrigin(
            displayPos, textSize, m_settings->pageNumber.position
        );
        // 应用透明度
        painter->setOpacity(m_settings->pageNumber.opacity);
        // 直接绘制文本
        painter->drawText(textOrigin, pageText);
    } catch (const std::exception& e) {
    }
    painter->restore();
}

void UnifiedPageRenderer::renderPageNumberOnly(QPainter* painter, const QRect& targetRect, int pageNumber, int totalPages)
{
    // Martin Fowler重构：仅绘制页码部分，用于局部更新
    // 避免整个页面重新渲染导致位置跳动
    
    if (!painter || !m_settings || pageNumber <= 0) {
        return;
    }
    
    // 计算页面布局
    PageLayout layout = calculatePageLayout(targetRect);
    
    // 只绘制页码，不绘制其他内容
    drawPageNumber(painter, layout, pageNumber, totalPages);
}

void UnifiedPageRenderer::drawHeaderFooter(QPainter* painter, const PageLayout& layout)
{
    // 页眉
    if (m_settings->header.enabled && !m_settings->header.text.isEmpty()) {
        painter->save();
        painter->setFont(m_settings->header.font);
        painter->setPen(m_settings->header.color);
        Qt::Alignment alignment = Qt::AlignVCenter;
        switch (m_settings->header.position) {
            case HeaderFooterPosition::Left:   alignment |= Qt::AlignLeft; break;
            case HeaderFooterPosition::Center: alignment |= Qt::AlignHCenter; break;
            case HeaderFooterPosition::Right:  alignment |= Qt::AlignRight; break;
        }
        painter->drawText(layout.headerArea, alignment, m_settings->header.text);
        painter->restore();
    }
    // 页脚
    if (m_settings->footer.enabled && !m_settings->footer.text.isEmpty()) {
        painter->save();
        painter->setFont(m_settings->footer.font);
        painter->setPen(m_settings->footer.color);
        Qt::Alignment alignment = Qt::AlignVCenter;
        switch (m_settings->footer.position) {
            case HeaderFooterPosition::Left:   alignment |= Qt::AlignLeft; break;
            case HeaderFooterPosition::Center: alignment |= Qt::AlignHCenter; break;
            case HeaderFooterPosition::Right:  alignment |= Qt::AlignRight; break;
        }
        painter->drawText(layout.footerArea, alignment, m_settings->footer.text);
        painter->restore();
    }
}
UnifiedPageRenderer::PageLayout UnifiedPageRenderer::calculatePageLayout(const QRect& targetRect) const
{
    PageLayout layout;
    layout.pageRect = targetRect;
    if (!m_settings) {
        layout.contentArea = targetRect;
        return layout;
    }
    // 检查是否为零边距模式
    bool isZeroMargin = (m_settings->margins.top <= 0.0 && 
                        m_settings->margins.bottom <= 0.0 && 
                        m_settings->margins.left <= 0.0 && 
                        m_settings->margins.right <= 0.0);
    if (isZeroMargin) {
        // 零边距模式：内容区域占满整个页面，模拟无边距打印机行为
        layout.contentArea = targetRect;
        // 清空边距区域
        for (int i = 0; i < 4; ++i) {
            layout.marginAreas[i] = QRect();
        }
        // 页眉页脚区域也设为空（零边距时通常不显示）
        layout.headerArea = QRect();
        layout.footerArea = QRect();
        layout.pageNumberArea = QRect();
        return layout;
    }
    // 正常边距模式：将毫米转换为像素
    double topMarginPx = mmToPixels(m_settings->margins.top, targetRect);
    double bottomMarginPx = mmToPixels(m_settings->margins.bottom, targetRect);
    double leftMarginPx = mmToPixels(m_settings->margins.left, targetRect);
    double rightMarginPx = mmToPixels(m_settings->margins.right, targetRect);
    // 计算内容区域
    layout.contentArea = QRect(
        targetRect.x() + (int)leftMarginPx,
        targetRect.y() + (int)topMarginPx,
        targetRect.width() - (int)(leftMarginPx + rightMarginPx),
        targetRect.height() - (int)(topMarginPx + bottomMarginPx)
    );
    // 计算边距区域
    layout.marginAreas[0] = QRect(targetRect.x(), targetRect.y(), targetRect.width(), (int)topMarginPx);  // 上边距
    layout.marginAreas[1] = QRect(targetRect.x(), targetRect.bottom() - (int)bottomMarginPx, targetRect.width(), (int)bottomMarginPx);  // 下边距
    layout.marginAreas[2] = QRect(targetRect.x(), targetRect.y(), (int)leftMarginPx, targetRect.height());  // 左边距
    layout.marginAreas[3] = QRect(targetRect.right() - (int)rightMarginPx, targetRect.y(), (int)rightMarginPx, targetRect.height());  // 右边距
    // 计算页眉页脚区域（在边距区域内）
    int headerFooterHeight = 30; // 默认高度
    layout.headerArea = QRect(layout.contentArea.x(), layout.marginAreas[0].y(),
                             layout.contentArea.width(), headerFooterHeight);
    layout.footerArea = QRect(layout.contentArea.x(), layout.marginAreas[1].bottom() - headerFooterHeight,
                             layout.contentArea.width(), headerFooterHeight);
    // 页码区域将根据位置设置计算 - 使用新的适配器系统
    layout.pageNumberArea = calculatePageNumberArea(layout, m_settings->pageNumber.position);
    return layout;
}
QRect UnifiedPageRenderer::calculatePageNumberArea(const PageLayout& layout, PagePositionSystem::Position position) const
{
    
    const int pageNumWidth = 80;
    const int pageNumHeight = 20;
    QRect baseRect;
    // 使用新的统一枚举系统 - Martin Fowler重构：消除Magic Number
    switch (position) {
        case PagePositionSystem::Position::TopLeft:
            baseRect = QRect(layout.marginAreas[2].right(), layout.marginAreas[0].y(),
                            pageNumWidth, pageNumHeight);
            break;
        case PagePositionSystem::Position::TopCenter:
            baseRect = QRect(layout.contentArea.x() + (layout.contentArea.width() - pageNumWidth) / 2,
                            layout.marginAreas[0].y(), pageNumWidth, pageNumHeight);
            break;
        case PagePositionSystem::Position::TopRight:
            baseRect = QRect(layout.marginAreas[3].x() - pageNumWidth, layout.marginAreas[0].y(),
                            pageNumWidth, pageNumHeight);
            break;
        case PagePositionSystem::Position::BottomLeft:
            baseRect = QRect(layout.marginAreas[2].right(), layout.marginAreas[1].bottom() - pageNumHeight,
                            pageNumWidth, pageNumHeight);
            break;
        case PagePositionSystem::Position::BottomCenter:
                        baseRect = QRect(layout.contentArea.x() + (layout.contentArea.width() - pageNumWidth) / 2,
                            layout.marginAreas[1].bottom() - pageNumHeight, pageNumWidth, pageNumHeight);
            break;
        case PagePositionSystem::Position::BottomRight:
            baseRect = QRect(layout.marginAreas[3].x() - pageNumWidth, layout.marginAreas[1].bottom() - pageNumHeight,
                            pageNumWidth, pageNumHeight);
            break;
        case PagePositionSystem::Position::Custom:
            // 自定义位置 - 基于BottomCenter应用偏移
            baseRect = QRect(layout.contentArea.x() + (layout.contentArea.width() - pageNumWidth) / 2,
                            layout.marginAreas[1].bottom() - pageNumHeight, pageNumWidth, pageNumHeight);
            if (m_settings) {
                // 使用网格系统的像素偏移
                QPointF offsetMM = m_settings->pageNumber.gridState.toMillimeterOffset();
                // 将毫米转换为像素偏移（这里需要根据实际DPI计算）
                double dpi = 96.0; // 或者使用实际的屏幕DPI
                QPointF offsetPixels(offsetMM.x() * dpi / 25.4, offsetMM.y() * dpi / 25.4);
                baseRect.translate(offsetPixels.x(), offsetPixels.y());
            }
            break;
        default:
            // 默认为底部居中
            baseRect = QRect(layout.contentArea.x() + (layout.contentArea.width() - pageNumWidth) / 2,
                            layout.marginAreas[1].bottom() - pageNumHeight, pageNumWidth, pageNumHeight);
            break;
    }

        return baseRect;
}
QString UnifiedPageRenderer::formatPageNumber(int pageNumber, int totalPages) const
{
    if (!m_settings) return QString::number(pageNumber);
    // Martin Fowler重构：使用PageNumberFormatter替代重复逻辑
    return m_settings->pageNumber.formatPageNumber(pageNumber, totalPages);
}
// 新增：精确的垂直流布局计算（从PageRenderer迁移）
QVector<QRect> UnifiedPageRenderer::computeVerticalFlowLayout(const QList<QList<QImage>>& columnImages,
    int columns, int columnWidth, int columnSpacing,
    int marginTop, int marginLeft, int marginBottom,
    int a4Width, int a4Height, int availableHeight,
    const QVector<int>* originalIndices,
    QHash<int, QRect>* outOriginalToRect,
    bool useLogicalAllocation) const
{
    QVector<QRect> resultRects;
    resultRects.reserve(columns * 8); // 预估
    // 计算统一的行数（多列布局中每列应该有相同的行数）
    int maxRowsPerColumn = 0;
    for (int col = 0; col < columns && col < columnImages.size(); col++) {
        maxRowsPerColumn = qMax(maxRowsPerColumn, columnImages[col].size());
    }
    // 计算每行的逻辑分配高度
    int logicalSlotHeight = maxRowsPerColumn > 0 ? availableHeight / maxRowsPerColumn : availableHeight;
    int seq = 0;
    for (int col = 0; col < columns; col++) {
        if (col >= columnImages.size()) break;
        int currentY = marginTop;
        int colX = marginLeft + col * (columnWidth + columnSpacing);
        for (int imgIndex = 0; imgIndex < columnImages[col].size(); imgIndex++) {
            QImage page = columnImages[col][imgIndex];
            if (page.isNull()) {
                QSize placeholderSize(columnWidth, qMin(600, availableHeight / 4));
                QRect rect;
                if (useLogicalAllocation) {
                    // 使用逻辑分配区域：占满整个槽位，但不超出边界
                    int actualSlotHeight = qMin(logicalSlotHeight, availableHeight - (currentY - marginTop));
                    rect = QRect(colX, currentY, columnWidth, actualSlotHeight);
                } else {
                    // 使用紧密内容区域：只占实际占位符大小
                    rect = QRect(colX + (columnWidth - placeholderSize.width()) / 2, currentY, placeholderSize.width(), placeholderSize.height());
                }
                resultRects.append(rect);
                if (outOriginalToRect && originalIndices && seq < originalIndices->size()) {
                    int originalPageIndex = (*originalIndices)[seq];
                    (*outOriginalToRect)[originalPageIndex] = QRect();
                }
                seq++;
                currentY += useLogicalAllocation ? logicalSlotHeight : (placeholderSize.height() + 10);
                continue;
            }
            QImage scaledPage = page.scaled(columnWidth, availableHeight,
                                          Qt::KeepAspectRatio,
                                          Qt::SmoothTransformation);
            QRect rect;
            if (useLogicalAllocation) {
                // 使用逻辑分配区域：占满整个槽位宽度，但不超出边界
                int actualSlotHeight = qMin(logicalSlotHeight, availableHeight - (currentY - marginTop));
                rect = QRect(colX, currentY, columnWidth, actualSlotHeight);
            } else {
                // 使用紧密内容区域：只占实际图像大小，无间距
                int imgX = colX + (columnWidth - scaledPage.width()) / 2;
                rect = QRect(imgX, currentY, scaledPage.width(), scaledPage.height());
            }
            resultRects.append(rect);
            if (outOriginalToRect && originalIndices && seq < originalIndices->size()) {
                int originalPageIndex = (*originalIndices)[seq];
                (*outOriginalToRect)[originalPageIndex] = rect;
            }
            seq++;
            // 关键修复：垂直流布局不添加额外间距，页面紧密排列
            currentY += useLogicalAllocation ? logicalSlotHeight : scaledPage.height();
        }
    }
    return resultRects;
}
// 新增：占位符绘制（从PageRenderer迁移）
void UnifiedPageRenderer::drawBeautifulPlaceholder(QPainter* painter, const QSize& size, int pageIndex, int x, int y)
{
    // 简化的占位符实现
    QImage placeholder(size, QImage::Format_ARGB32);
    placeholder.fill(QColor(240, 240, 240));
    painter->drawImage(x, y, placeholder);
}
// 新增：页面计数方法（从PageRenderer迁移）
int UnifiedPageRenderer::pagesPerComposite(LayoutMode mode) const
{
    switch (mode) {
        case LayoutMode::TwoColumns:
            return 4; // 2列 × 2行
        case LayoutMode::ThreeColumns:
            return 9; // 3列 × 3行
        case LayoutMode::SingleColumn:
        default:
            return 1; // 单栏每页一个
    }
}
// 新增：带布局信息的页面重排（兼容PageRenderer接口）
UnifiedPageRenderer::CompositeLayout UnifiedPageRenderer::rearrangeWithLayout(const QList<QImage>& originalPages, LayoutMode mode)
{
    CompositeLayout result;
    result.pages = rearrangePagesForColumns(originalPages, mode);
    // 实现布局矩形计算逻辑
    // 这里需要根据mode和页面信息计算每个原始页面在组合页面中的位置
    if (mode != LayoutMode::SingleColumn && !originalPages.isEmpty()) {
        // 对于多栏模式，需要计算布局矩形
        int columns = (mode == LayoutMode::TwoColumns) ? 2 : 3;
        int maxPagesPerColumn = (mode == LayoutMode::TwoColumns) ? 2 : 3;
        int pagesPerComposite = columns * maxPagesPerColumn;
        // 计算组合页面数量
        int totalPages = originalPages.size();
        int compositePageCount = (totalPages + pagesPerComposite - 1) / pagesPerComposite;
        // 为每个组合页面计算布局矩形
        for (int compositeIndex = 0; compositeIndex < compositePageCount; ++compositeIndex) {
            QHash<int, QRect> pageRects;
            // 计算当前组合页面包含的原始页面范围
            int startPageIndex = compositeIndex * pagesPerComposite;
            int endPageIndex = qMin(startPageIndex + pagesPerComposite, totalPages);
            // 为每个原始页面计算在组合页面中的位置
            // 使用与实际渲染一致的布局参数
            int a4Width = 1240;
            int a4Height = 1754;
            int avgMargin = 10; // 10mm边距
            int marginSize = DPICalculationService::mmToPixels(avgMargin, 150.0);
            int columnSpacing = 30;
            
            // 计算列宽度（与实际渲染一致）
            int columnWidth = (a4Width - 2 * marginSize - (columns - 1) * columnSpacing) / columns;
            int availableHeight = a4Height - 2 * marginSize;
            int rowHeight = availableHeight / maxPagesPerColumn;
            
            for (int originalIndex = startPageIndex; originalIndex < endPageIndex; ++originalIndex) {
                int relativeIndex = originalIndex - startPageIndex;
                int col = relativeIndex / maxPagesPerColumn;
                int row = relativeIndex % maxPagesPerColumn;
                
                // 使用与实际渲染一致的布局计算
                int rectX = marginSize + col * (columnWidth + columnSpacing);
                int rectY = marginSize + row * rowHeight;
                int rectW = columnWidth;
                int rectH = rowHeight;
                pageRects[originalIndex] = QRect(rectX, rectY, rectW, rectH);
            }
            result.layoutRects[compositeIndex] = pageRects;
        }
    }
    return result;
}
double UnifiedPageRenderer::mmToPixels(double mm, const QRect& targetRect) const
{
    // 为了屏幕渲染稳定性，始终使用与目标矩形相关的逻辑像素映射，
    // 保证切换DPI时画布与内容位置不抖动（只改变清晰度）。
    double pixelsPerMmWidth = targetRect.width() / A4_WIDTH_MM;
    double pixelsPerMmHeight = targetRect.height() / A4_HEIGHT_MM;
    return mm * (pixelsPerMmWidth + pixelsPerMmHeight) / 2.0;
}
// Martin Fowler重构：Strategy Pattern - DPI图像增强实现
QImage UnifiedPageRenderer::applyDPIEnhancement(const QImage& source) const
{
    if (!m_settings || source.isNull()) {
        return source;
    }
    int dpi = m_settings->standardDPI;
    // 低DPI：直接返回原图，保持性能
    if (dpi <= 96) {
        return source;
    }
    // 中DPI：轻度锐化
    if (dpi >= 150 && dpi < 300) {
        return applySharpening(source, 0.5);
    }
    // 高DPI：强度锐化
    if (dpi >= 300) {
        return applySharpening(source, 1.0);
    }
    return source;
}
QImage UnifiedPageRenderer::applySharpening(const QImage& source, double intensity) const
{
    if (source.isNull() || intensity <= 0.0) {
        return source;
    }
    // 优化的锐化滤波器实现，提升300 DPI效果
    QImage result = source.copy();
    // 使用更温和的锐化算法，避免过度锐化
    const double kernelFactor = 0.25; // 降低锐化强度，避免噪点
    for (int y = 1; y < result.height() - 1; ++y) {
        for (int x = 1; x < result.width() - 1; ++x) {
            QRgb center = result.pixel(x, y);
            QRgb top = result.pixel(x, y - 1);
            QRgb bottom = result.pixel(x, y + 1);
            QRgb left = result.pixel(x - 1, y);
            QRgb right = result.pixel(x + 1, y);
            // 温和的拉普拉斯锐化，减少过度处理
            int r = qBound(0, qRed(center) + static_cast<int>(intensity * kernelFactor * 
                (4 * qRed(center) - qRed(top) - qRed(bottom) - qRed(left) - qRed(right))), 255);
            int g = qBound(0, qGreen(center) + static_cast<int>(intensity * kernelFactor * 
                (4 * qGreen(center) - qGreen(top) - qGreen(bottom) - qGreen(left) - qGreen(right))), 255);
            int b = qBound(0, qBlue(center) + static_cast<int>(intensity * kernelFactor * 
                (4 * qBlue(center) - qBlue(top) - qBlue(bottom) - qBlue(left) - qBlue(right))), 255);
            result.setPixel(x, y, qRgb(r, g, b));
        }
    }
    return result;
}
// 新增：多栏布局支持（从PageRenderer迁移）
QList<QImage> UnifiedPageRenderer::rearrangePagesForColumns(const QList<QImage>& originalPages, LayoutMode mode)
{
    
    if (originalPages.isEmpty()) {
        return originalPages;
    }
    
    QList<QImage> result;
    switch (mode) {
        case LayoutMode::SingleColumn:
            result = originalPages;
            break;
        case LayoutMode::TwoColumns:
            result = rearrangeForTwoColumns(originalPages);
            break;
        case LayoutMode::ThreeColumns:
            result = rearrangeForThreeColumns(originalPages);
            break;
        default:
            result = originalPages;
            break;
    }
    
    return result;
}
// 新增：组合页面生成（从PageRenderer迁移）
QImage UnifiedPageRenderer::composeCompositePageAt(const QList<QImage>& originalPages, int compositeIndex, LayoutMode mode)
{
    
    if (originalPages.isEmpty()) {
        return QImage();
    }
    int columns;
    int maxPagesPerColumn;
    switch (mode) {
        case LayoutMode::TwoColumns:
            columns = 2;
            maxPagesPerColumn = 2;
            break;
        case LayoutMode::ThreeColumns:
            columns = 3;
            maxPagesPerColumn = 3;
            break;
        case LayoutMode::SingleColumn:
        default:
            // 单栏模式直接返回对应页面
            if (compositeIndex >= 0 && compositeIndex < originalPages.size()) {
                return originalPages[compositeIndex];
            }
            return QImage();
    }
    int pagesPerResultPage = columns * maxPagesPerColumn;
    int startPageIndex = compositeIndex * pagesPerResultPage;
    // 收集这个组合页面的所有源页面（使用列优先排列）
    QList<QList<QImage>> columnImages(columns);
    QList<int> columnImageWidths(columns);
    for (int col = 0; col < columns; col++) {
        QList<QImage> columnPages;
        int maxWidth = 0;
        for (int row = 0; row < maxPagesPerColumn; row++) {
            int pageIndex = startPageIndex + col * maxPagesPerColumn + row;
            if (pageIndex < originalPages.size()) {
                QImage page = originalPages[pageIndex];
                columnPages.append(page);
                if (!page.isNull()) {
                    maxWidth = qMax(maxWidth, page.width());
                }
            }
        }
        columnImages[col] = columnPages;
        columnImageWidths[col] = maxWidth > 0 ? maxWidth : 800;
    }
    // 屏幕预览：使用稳定的画布尺寸与边距像素，避免切换DPI导致抖动
    const int stableA4Width = 1240;  // 约150 DPI A4宽
    const int stableA4Height = 1754; // 约150 DPI A4高
    int a4Width = stableA4Width;
    int a4Height = stableA4Height;
    // 边距像素基于稳定DPI（150），避免随面板DPI变化
    int marginSize = 0;
    int columnSpacing = 30; // 默认列间距
    if (m_settings) {
        double avgMargin = MarginCalculationService::calculateAverageMargin(m_settings->margins);
        marginSize = DPICalculationService::mmToPixels(avgMargin, 150.0);
        
        
        // 零边距模式：使用较小的列间距，避免浪费空间
        if (MarginCalculationService::isZeroMargin(m_settings->margins)) {
            columnSpacing = 15; // 零边距时使用更小的列间距
        } else {
        }
    } else {
    }
    // 渲染组合页面
    int columnWidth = (a4Width - 2 * marginSize - (columns - 1) * columnSpacing) / columns;
    int availableHeight = a4Height - 2 * marginSize;
    
    
    // 创建原始索引数组，用于高亮判断
    QVector<int> originalIndices;
    for (int col = 0; col < columns; col++) {
        for (int row = 0; row < maxPagesPerColumn; row++) {
            int pageIndex = startPageIndex + col * maxPagesPerColumn + row;
            if (pageIndex < originalPages.size()) {
                originalIndices.append(pageIndex);
            }
        }
    }
    
    QImage result = renderVerticalFlowLayout(columnImages, columnImageWidths,
                                           columns, columnWidth, columnSpacing,
                                           marginSize, marginSize, marginSize,
                                           a4Width, a4Height, availableHeight,
                                           &originalIndices, nullptr);
    return result;
}
// 新增：垂直流布局渲染（从PageRenderer迁移）
QImage UnifiedPageRenderer::renderVerticalFlowLayout(const QList<QList<QImage>>& columnImages,
                                                    const QList<int>& columnImageWidths,
                                                    int columns, int columnWidth, int columnSpacing,
                                                    int marginTop, int marginLeft, int marginBottom,
                                                    int a4Width, int a4Height, int availableHeight,
                                                    const QVector<int>* originalIndices,
                                                    QHash<int, QRect>* outOriginalToRect)
{
    // 计算高亮矩形（使用紧密内容区域，精确覆盖页面内容）
    QHash<int, QRect> calcMap;
    QHash<int, QRect>* mapOut = outOriginalToRect ? outOriginalToRect : &calcMap;
    QVector<QRect> drawRects = computeVerticalFlowLayout(columnImages,
                                                         columns, columnWidth, columnSpacing,
                                                         marginTop, marginLeft, marginBottom,
                                                         a4Width, a4Height, availableHeight,
                                                         originalIndices, mapOut, false);
    // 将列优先图像展平与矩形对齐
    QVector<QImage> flatImages;
    for (int col = 0; col < columns; ++col) {
        if (col >= columnImages.size()) break;
        for (int i = 0; i < columnImages[col].size(); ++i) {
            flatImages.append(columnImages[col][i]);
        }
    }
    // 创建A4画布
    QImage combinedPage(a4Width, a4Height, QImage::Format_RGB32);
    combinedPage.fill(QColor(255, 255, 255));
    QPainter painter(&combinedPage);
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
    int n = qMin(drawRects.size(), flatImages.size());
    for (int k = 0; k < n; ++k) {
        const QRect& r = drawRects[k];
        const QImage& page = flatImages[k];
        if (page.isNull()) {
            drawBeautifulPlaceholder(&painter, r.size(), k, r.x(), r.y());
            continue;
        }
        if (page.size() == r.size()) {
            painter.drawImage(r.topLeft(), page);
        } else {
            QImage scaled = page.scaled(r.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
            painter.drawImage(r.topLeft(), scaled);
        }
        
        // 检查是否需要绘制高亮
        if (m_hasHighlight && originalIndices && k < originalIndices->size()) {
            int originalIndex = (*originalIndices)[k];
            if (originalIndex == m_highlightedThumbnailIndex) {
                // 绘制高亮矩形
                painter.setPen(QPen(QColor(0, 122, 255, 180), 3, Qt::SolidLine));
                painter.setBrush(QBrush(QColor(0, 122, 255, 30)));
                painter.drawRect(r);
                // 绘制内边框
                painter.setPen(QPen(QColor(0, 122, 255, 200), 1, Qt::SolidLine));
                painter.setBrush(Qt::NoBrush);
                painter.drawRect(r.adjusted(1, 1, -1, -1));
            }
        }
    }
    painter.end();
    return combinedPage;
}
// 私有辅助方法
QList<QImage> UnifiedPageRenderer::rearrangeForTwoColumns(const QList<QImage>& originalPages)
{
    QList<QImage> result = rearrangePagesInColumns(originalPages, 2, 2);
    return result;
}
QList<QImage> UnifiedPageRenderer::rearrangeForThreeColumns(const QList<QImage>& originalPages)
{
    return rearrangePagesInColumns(originalPages, 3, 3);
}
QList<QImage> UnifiedPageRenderer::rearrangePagesInColumns(const QList<QImage>& originalPages, 
                                                          int columns, int maxPagesPerColumn)
{
    
    QList<QImage> result;
    if (originalPages.isEmpty() || columns <= 0 || maxPagesPerColumn <= 0) {
        return result;
    }
    int totalPages = originalPages.size();
    int pagesPerResultPage = columns * maxPagesPerColumn;
    int resultPages = (totalPages + pagesPerResultPage - 1) / pagesPerResultPage;
    
    
    for (int resultPageIndex = 0; resultPageIndex < resultPages; ++resultPageIndex) {
        QImage compositePage = composeCompositePageAt(originalPages, resultPageIndex, 
                                                     columns == 2 ? LayoutMode::TwoColumns : LayoutMode::ThreeColumns);
        if (compositePage.isNull()) {
        } else {
        }
        result.append(compositePage);
    }
    
    return result;
}
// =================== 高亮功能实现（从PageView迁移） ===================
void UnifiedPageRenderer::setHighlightInfo(int thumbnailIndex, int totalThumbnails, int columnMode)
{
    m_highlightedThumbnailIndex = thumbnailIndex;
    m_totalThumbnails = totalThumbnails;
    m_columnMode = columnMode;
    m_hasHighlight = true;
}
void UnifiedPageRenderer::clearHighlight()
{
    m_hasHighlight = false;
    m_highlightedThumbnailIndex = -1;
}
QRect UnifiedPageRenderer::calculateHighlightRect(int pageWidth, int pageHeight, int currentPage) const
{
    
    if (!m_hasHighlight || m_columnMode == 1) {
        return QRect(); // 单栏模式不需要高亮
    }
    // 优先使用精确矩形
    if (currentPage >= 0) {
        
        // 修复：currentPage是全局页码，需要转换为组合页面索引
        // m_accurateLayoutRects的键是组合页面索引，不是原始页面索引
        int columns = m_columnMode;
        int maxPerCol = m_columnMode;
        int pagesPerResultPage = columns * maxPerCol;
        
        // 计算组合页面索引：缩略图索引 / 每组合页面的缩略图数
        int compositePageIndex = m_highlightedThumbnailIndex / pagesPerResultPage;
        
        auto pageIt = m_accurateLayoutRects.find(compositePageIndex);
        if (pageIt != m_accurateLayoutRects.end()) {
            const QHash<int, QRect>& map = pageIt.value();
            auto it = map.find(m_highlightedThumbnailIndex);
            if (it != map.end() && it.value().isValid() && it.value().width() > 0 && it.value().height() > 0) {
                return it.value();
            } else {
            }
        } else {
        }
    }
    // 修复：使用与实际渲染一致的布局参数
    int a4Width = 1240;
    int a4Height = 1754;
    int columns = m_columnMode;
    int maxPerCol = m_columnMode;
    int pagesPerResultPage = columns * maxPerCol;
    
    // 使用与实际渲染一致的边距计算
    int avgMargin = 10; // 10mm边距
    int marginSize = DPICalculationService::mmToPixels(avgMargin, 150.0);
    int columnSpacing = 30;
    
    // 计算列宽度（与实际渲染一致）
    int columnWidth = (a4Width - 2 * marginSize - (columns - 1) * columnSpacing) / columns;
    int availableHeight = a4Height - 2 * marginSize;
    
    // 使用缩略图索引直接计算组合页面索引
    int compositePageIndex = m_highlightedThumbnailIndex / pagesPerResultPage;
    int pageStartThumbnail = compositePageIndex * pagesPerResultPage;
    int pageEndThumbnail = pageStartThumbnail + pagesPerResultPage - 1;
    
    
    // 检查缩略图是否在当前组合页面范围内
    if (m_highlightedThumbnailIndex < pageStartThumbnail || m_highlightedThumbnailIndex > pageEndThumbnail) {
        return QRect(); // 不在当前页面内
    }
    
    // 计算缩略图在当前组合页面内的相对索引
    int relativeThumbnailIndex = m_highlightedThumbnailIndex - pageStartThumbnail;
    
    // 计算列和行（列优先布局）
    int column = relativeThumbnailIndex / maxPerCol;
    int row = relativeThumbnailIndex % maxPerCol;
    
    // 计算列的位置（与实际渲染一致）
    int colX = marginSize + column * (columnWidth + columnSpacing);
    
    // 计算行高（与实际渲染一致）
    int rowHeight = availableHeight / maxPerCol;
    int rowY = marginSize + row * rowHeight;
    
    QRect result(colX, rowY, columnWidth, rowHeight);
    return result;
}
void UnifiedPageRenderer::drawHighlightRectangles(QPainter* painter, const QRect& pageRect, int currentPage) const
{
    if (!m_hasHighlight) {
        return;
    }
    QRect highlightRect = calculateHighlightRect(pageRect.width(), pageRect.height(), currentPage);
    if (highlightRect.isValid()) {
        // 创建专业的高亮效果：iOS蓝色边框 + 半透明iOS蓝色填充
        QPen highlightPen(QColor(0, 122, 255), 3, Qt::SolidLine);  // iOS蓝色，3像素实线
        QBrush highlightBrush(QColor(0, 122, 255, 40));            // 半透明iOS蓝色填充
        painter->setPen(highlightPen);
        painter->setBrush(highlightBrush);
        painter->drawRect(highlightRect);
        // 添加内边框效果，增强专业感
        QRect innerRect = highlightRect.adjusted(2, 2, -2, -2);
        if (innerRect.isValid() && innerRect.width() > 0 && innerRect.height() > 0) {
            QPen innerPen(QColor(255, 255, 255, 180), 1, Qt::SolidLine);  // 白色内边框
            painter->setPen(innerPen);
            painter->setBrush(Qt::NoBrush);
            painter->drawRect(innerRect);
        }
    }
}
// =================== 智能缩放策略实现（从PageView迁移） ===================
UnifiedPageRenderer::ZoomStrategy UnifiedPageRenderer::calculateOptimalZoomStrategy(const QImage& image, const QSize& viewSize) const
{
    if (image.isNull() || viewSize.width() <= 0 || viewSize.height() <= 0) {
        return SmartFit;
    }
    double imageRatio = static_cast<double>(image.width()) / image.height();
    double viewRatio = static_cast<double>(viewSize.width()) / viewSize.height();
    if (shouldPreferFitWidth(imageRatio, viewRatio, image, viewSize)) {
        return FitWidth;
    } else {
        return FitHeight;
    }
}
double UnifiedPageRenderer::calculateOptimalZoomRatio(const QImage& image, const QSize& viewSize, ZoomStrategy strategy) const
{
    if (image.isNull() || viewSize.width() <= 0 || viewSize.height() <= 0) {
        return 1.0;
    }
    double widthRatio = static_cast<double>(viewSize.width()) / image.width();
    double heightRatio = static_cast<double>(viewSize.height()) / image.height();
    switch (strategy) {
        case FitWidth:
            return widthRatio;
        case FitHeight:
            return heightRatio;
        case SmartFit:
        default:
            return qMin(widthRatio, heightRatio);
    }
}
bool UnifiedPageRenderer::shouldPreferFitWidth(double imageRatio, double viewRatio, const QImage& image, const QSize& viewSize) const
{
    // Martin Fowler重构：基于用户体验优化的智能决策
    // 策略1：极长图（高度 > 2倍宽度）优先适合宽度，便于阅读
    if (imageRatio < 0.5) {  // 宽高比 < 1:2，真正的长图
        return true;
    }
    // 策略2：超宽图（宽度 > 2倍高度）优先适合高度
    if (imageRatio > 2.0) {  // 宽高比 > 2:1
        return false;
    }
    // 策略3：长图区间（0.5-0.8）优先适合高度，避免过宽显示
    if (imageRatio >= 0.5 && imageRatio < 0.8) {  // 包括2:3到4:5的长图
        return false;  // 适合高度
    }
    // 策略4：接近方形的图片，选择能完整显示的模式
    if (imageRatio >= 0.8 && imageRatio <= 1.25) {  // 接近方形 4:5 到 5:4
        double widthScale = static_cast<double>(viewSize.width()) / image.width();
        double heightScale = static_cast<double>(viewSize.height()) / image.height();
        // 选择缩放比例更小的（能完整显示的）
        return widthScale <= heightScale;
    }
    // 策略5：其他情况，根据长宽比与视口比例的关系决定
    return imageRatio < viewRatio;
}
// =================== 预览渲染优化实现（从PageView迁移） ===================
QImage UnifiedPageRenderer::renderForPreview(const QImage& originalImage, int pageIndex, const QSize& targetSize, int totalPages) const
{
    if (originalImage.isNull() || !m_settings) {
        return originalImage;
    }
    // 设置页面内容
    const_cast<UnifiedPageRenderer*>(this)->setPageContent(originalImage);
    // 性能优化：预览渲染固定150 DPI，不读取用户DPI设置
    // 这确保PageView显示性能和稳定性，用户DPI设置仅影响PDF导出
    const double FIXED_PREVIEW_DPI = 150.0;
    const double MM_PER_INCH = 25.4;
    const double A4_WIDTH_MM = 210.0;
    const double A4_HEIGHT_MM = 297.0;
    // 直接计算150 DPI下的A4像素尺寸
    int a4WidthPixels = qRound((A4_WIDTH_MM / MM_PER_INCH) * FIXED_PREVIEW_DPI);
    int a4HeightPixels = qRound((A4_HEIGHT_MM / MM_PER_INCH) * FIXED_PREVIEW_DPI);
    const QSize a4PreviewSize(a4WidthPixels, a4HeightPixels);
    QImage previewImage(a4PreviewSize, QImage::Format_ARGB32);
    previewImage.fill(Qt::white);
    QPainter painter(&previewImage);
    const_cast<UnifiedPageRenderer*>(this)->renderToWidget(&painter, previewImage.rect(), pageIndex + 1, totalPages);
    painter.end();
    return previewImage;
}
QImage UnifiedPageRenderer::renderForPreviewWithGlobalPage(const QImage& originalImage, int pageIndex, const QSize& targetSize, int globalPage, int totalPages) const
{
    if (originalImage.isNull() || !m_settings) {
        return originalImage;
    }
    // 设置页面内容
    const_cast<UnifiedPageRenderer*>(this)->setPageContent(originalImage);
    // 性能优化：预览渲染固定150 DPI，不读取用户DPI设置
    // 这确保PageView显示性能和稳定性，用户DPI设置仅影响PDF导出
    const double FIXED_PREVIEW_DPI = 150.0;
    const double MM_PER_INCH = 25.4;
    const double A4_WIDTH_MM = 210.0;
    const double A4_HEIGHT_MM = 297.0;
    // 直接计算150 DPI下的A4像素尺寸
    int a4WidthPixels = qRound((A4_WIDTH_MM / MM_PER_INCH) * FIXED_PREVIEW_DPI);
    int a4HeightPixels = qRound((A4_HEIGHT_MM / MM_PER_INCH) * FIXED_PREVIEW_DPI);
    const QSize a4PreviewSize(a4WidthPixels, a4HeightPixels);
    QImage previewImage(a4PreviewSize, QImage::Format_ARGB32);
    previewImage.fill(Qt::white);
    QPainter painter(&previewImage);
    if (globalPage > 0) {
        const_cast<UnifiedPageRenderer*>(this)->renderToWidget(&painter, previewImage.rect(), globalPage, totalPages);
    } else {
        // 只渲染页面内容，不渲染页码
        const_cast<UnifiedPageRenderer*>(this)->renderToWidget(&painter, previewImage.rect(), 0, totalPages);
    }
    painter.end();
    return previewImage;
}
QImage UnifiedPageRenderer::renderForExport(const QImage& originalImage, int pageIndex, int totalPages) const
{
    if (originalImage.isNull() || !m_settings) {
        return originalImage;
    }
    // 设置页面内容
    const_cast<UnifiedPageRenderer*>(this)->setPageContent(originalImage);
    // 导出模式：创建A4尺寸的图像用于PDF
    // 使用标准A4比例，这将与PDF输出保持一致
    QSize a4Size(595, 842); // A4的点数尺寸（72 DPI时）
    QImage exportImage(a4Size, QImage::Format_ARGB32);
    exportImage.fill(Qt::white);
    QPainter painter(&exportImage);
    const_cast<UnifiedPageRenderer*>(this)->renderToWidget(&painter, exportImage.rect(), pageIndex + 1, totalPages);
    painter.end();
    return exportImage;
}
// === Martin Fowler重构：使用PageRenderContext的新实现 ===
QImage UnifiedPageRenderer::renderForPreviewWithContext(const QImage& originalImage, const PageRenderContext& context) const
{
    if (originalImage.isNull() || !m_settings) {
        return originalImage;
    }
    // 使用PageRenderContext中的全局页码信息
    // 直接使用PageRenderContext中的全局页码信息
    return renderForPreviewWithGlobalPage(originalImage, context.getArrayIndex(),
                                        context.getViewportSize(), 
                                        context.getGlobalPage(), 
                                        context.getTotalPages());
}
QImage UnifiedPageRenderer::renderForExportWithContext(const QImage& originalImage, const PageRenderContext& context) const
{
    if (originalImage.isNull() || !m_settings) {
        return originalImage;
    }
    // 委托给旧方法，实现渐进式重构
    return renderForExport(originalImage, context.getArrayIndex(), context.getTotalPages());
}
// =================== 精确布局矩形支持实现（从PageView迁移） ===================
void UnifiedPageRenderer::setAccurateLayoutRects(const QHash<int, QHash<int, QRect>>& layoutRects)
{
    m_accurateLayoutRects = layoutRects;
}
// ========== 缩放策略方法组实现 ==========
UnifiedPageRenderer::ZoomStrategy UnifiedPageRenderer::determineOptimalZoomStrategy(const QImage& image, const QSize& viewSize) const
{
    return calculateOptimalZoomStrategy(image, viewSize);
}
double UnifiedPageRenderer::computeZoomRatio(const QImage& image, const QSize& viewSize, ZoomStrategy strategy) const
{
    return calculateOptimalZoomRatio(image, viewSize, strategy);
}
bool UnifiedPageRenderer::evaluatePreferFitWidth(double imageRatio, double viewRatio, const QImage& image, const QSize& viewSize) const
{
    return shouldPreferFitWidth(imageRatio, viewRatio, image, viewSize);
}
// ========== 多栏布局方法组实现 ==========
QImage UnifiedPageRenderer::composeMultiColumnPage(const QList<QImage>& originalPages, int compositeIndex, LayoutMode mode)
{
    return composeCompositePageAt(originalPages, compositeIndex, mode);
}
QImage UnifiedPageRenderer::renderVerticalFlowComposition(const QList<QList<QImage>>& columnImages,
                                                        const QList<int>& columnImageWidths,
                                                        int columns, int columnWidth, int columnSpacing,
                                                        int marginTop, int marginLeft, int marginBottom,
                                                        int a4Width, int a4Height, int availableHeight,
                                                        const QVector<int>* originalIndices,
                                                        QHash<int, QRect>* outOriginalToRect)
{
    return renderVerticalFlowLayout(columnImages, columnImageWidths, columns, columnWidth, columnSpacing,
                                  marginTop, marginLeft, marginBottom, a4Width, a4Height, availableHeight,
                                  originalIndices, outOriginalToRect);
}
// ========== 高亮功能方法组实现 ==========
QRect UnifiedPageRenderer::computeHighlightRect(int pageWidth, int pageHeight, int currentPage) const
{
    return calculateHighlightRect(pageWidth, pageHeight, currentPage);
}
void UnifiedPageRenderer::renderHighlightRectangles(QPainter* painter, const QRect& pageRect, int currentPage) const
{
    drawHighlightRectangles(painter, pageRect, currentPage);
}
// ========== 预览渲染方法组实现 ==========
QImage UnifiedPageRenderer::generatePreviewImage(const QImage& originalImage, int pageIndex, const QSize& targetSize, int totalPages) const
{
    return renderForPreview(originalImage, pageIndex, targetSize, totalPages);
}
QImage UnifiedPageRenderer::generateExportImage(const QImage& originalImage, int pageIndex, int totalPages) const
{
    return renderForExport(originalImage, pageIndex, totalPages);
}
void UnifiedPageRenderer::clearAccurateLayoutRects()
{
    m_accurateLayoutRects.clear();
}
// ========== 传统渲染系统 ==========
void UnifiedPageRenderer::setProcessingDpi(double dpi)
{
    // 传统渲染系统不需要动态DPI设置
    Q_UNUSED(dpi)
}
double UnifiedPageRenderer::getProcessingDpi() const
{
    return 300.0; // 传统渲染系统默认DPI
}
void UnifiedPageRenderer::autoConfigureForDisplay(QScreen* screen)
{
    // 传统渲染系统不需要自动配置
    Q_UNUSED(screen)
}
bool UnifiedPageRenderer::verifyWYSIWYG() const
{
    // 传统渲染系统始终保证WYSIWYG
    return true;
}
QString UnifiedPageRenderer::getDebugInfo() const
{
    QString info;
    QTextStream stream(&info);
    stream << "=== UnifiedPageRenderer 调试信息 ===" << Qt::endl;
    stream << "渲染系统: 传统渲染模式" << Qt::endl;
    if (m_settings) {
        stream << QString("处理设置DPI: %1").arg(m_settings->standardDPI) << Qt::endl;
    }
    return info;
}
// ========== 传统渲染方法（降级使用） ==========
void UnifiedPageRenderer::renderToWidgetLegacy(QPainter* painter, const QRect& targetRect, const QImage& content,
                                              int pageNumber, int totalPages)
{
    if (!painter || content.isNull()) return;
    // 使用传统渲染逻辑
    setPageContent(content);
    renderToWidget(painter, targetRect, pageNumber, totalPages);
}
void UnifiedPageRenderer::renderToPDFLegacy(QPdfWriter* writer, QPainter* painter, const QImage& content,
                                           int pageNumber, int totalPages)
{
    if (!writer || !painter || content.isNull()) return;
    // 使用传统PDF渲染逻辑
    setPageContent(content);
    renderToPDFLegacyDirect(writer, painter, pageNumber, totalPages);
}
// ========== WYSIWYG验证机制 ==========
QString UnifiedPageRenderer::getWYSIWYGReport() const
{
    QString report;
    QTextStream stream(&report);
    stream << "=== WYSIWYG验证报告 ===" << Qt::endl;
    stream << QString("验证时间: %1").arg(QDateTime::currentDateTime().toString()) << Qt::endl;
    stream << "渲染系统: 传统渲染模式" << Qt::endl;
    stream << "WYSIWYG验证: ✅ 通过 (传统渲染保证一致性)" << Qt::endl;
    return report;
}